<template>
  <div
    style="
      width: 100%;
      height: 100%;
      background-color: #f0f2f5;
      padding: 20px 0 0;
    "
  >
    <!-- Header区域 -->
    <el-row :gutter="24">
      <el-col :span="24">
        <el-card style="margin-bottom: 10px">
          <div>
            距离考试结束还有：
            <span style="color: #ff0000; font-weight: 700">{{
              timerDisplay
            }}</span>
          </div>
          <el-button
            :loading="loading"
            style="float: right; margin-top: -10px; margin-left: 10px"
            type="primary"
            icon="el-icon-plus"
            @click="handHandExamPre()"
          >
            {{ handleText }}
          </el-button>
          <el-button
            style="float: right; margin-top: -10px; margin-right: 10px"
            type="default"
            @click="confirmReturn()"
          >
            返回首页
          </el-button>
        </el-card>
      </el-col>

      <!-- 答题卡区域 -->
      <el-col :span="5" :xs="24" style="margin-bottom: 10px">
        <el-card class="content-h">
          <p class="card-title">答题卡</p>
          <el-row :gutter="24" class="card-line" style="padding-left: 10px">
            <el-tag type="info">未作答</el-tag>
            <el-tag type="success">已作答</el-tag>
            <el-tag type="warning">当前题目</el-tag>
          </el-row>

          <!-- 单选题答题卡 -->
          <question-card-section
            v-if="hasQuestions(paperData.radioList)"
            title="单选题"
            :questions="paperData.radioList"
            :current-item="cardItem"
            @select-question="handSave"
          />

          <!-- 多选题答题卡 -->
          <question-card-section
            v-if="hasQuestions(paperData.multiList)"
            title="多选题"
            :questions="paperData.multiList"
            :current-item="cardItem"
            @select-question="handSave"
          />

          <!-- 判断题答题卡 -->
          <question-card-section
            v-if="hasQuestions(paperData.judgeList)"
            title="判断题"
            :questions="paperData.judgeList"
            :current-item="cardItem"
            @select-question="handSave"
          />

          <!-- 简答题答题卡 -->
          <question-card-section
            v-if="hasQuestions(paperData.saqList)"
            title="简答题"
            :questions="paperData.saqList"
            :current-item="cardItem"
            @select-question="handSave"
          />
        </el-card>
      </el-col>

      <!-- 单题区域 -->
      <el-col :span="19" :xs="24">
        <el-card class="qu-content content-h">
          <!-- 题干 -->
          <p v-if="quData.content">
            {{ quData.sort + 1 }}.{{ quData.content }}
          </p>
          <p v-if="quData.image">
            <el-image :src="quData.image" style="max-width: 200px" />
          </p>

          <!-- 单选和判断题选项区域 -->
          <div v-if="quData.quType === 1 || quData.quType === 3">
            <el-radio-group v-model="radioValue">
              <el-radio
                v-for="item in quData.answerList"
                :key="item.id"
                :label="item.id"
              >
                {{ numberToLetter(item.sort) }}.{{ item.content }}
                <div v-if="item.image" style="clear: both">
                  <el-image :src="item.image" style="max-width: 200px" />
                </div>
              </el-radio>
            </el-radio-group>
          </div>

          <!-- 多选题区域 -->
          <div v-if="quData.quType === 2">
            <el-checkbox-group v-model="multiValue">
              <el-checkbox
                v-for="item in quData.answerList"
                :key="item.id"
                :label="item.id"
              >
                {{ numberToLetter(item.sort) }}.{{ item.content }}
                <div v-if="item.image" style="clear: both">
                  <el-image :src="item.image" style="max-width: 200px" />
                </div>
              </el-checkbox>
            </el-checkbox-group>
          </div>

          <!-- 简答题区域 -->
          <div v-if="quData.quType === 4">
            <el-input
              v-model="saqTextarea"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
              placeholder="请输入内容"
            />
          </div>

          <!-- 提交前汇总对话框 -->
          <exam-summary-dialog
            v-model:visible="examPreVisible"
            :record-data="recordData"
            @close="handleClose"
            @confirm="doHandler"
          />

          <!-- 导航按钮 -->
          <div style="margin-top: 20px">
            <el-button
              v-if="showPrevious"
              type="primary"
              icon="el-icon-back"
              @click="handPrevious()"
            >
              上一题
            </el-button>

            <el-button
              v-if="showNext"
              type="warning"
              icon="el-icon-right"
              @click="handNext()"
            >
              下一题
            </el-button>

            <!-- 添加最后一题的提交按钮 -->
            <el-button
              v-if="!showNext && cardItem.sort === allItem.length - 1"
              type="success"
              icon="el-icon-check"
              @click="submitLastAnswer()"
            >
              提交答案
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 切屏弹窗 -->
    <el-dialog
      title="提示"
      v-model="tipsFlag"
      width="480px"
      class="commonDialog multi clickLight"
      center
      :close-on-click-modal="false"
    >
      {{ examMeg }}
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, nextTick, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import {
  quDetail,
  handExam,
  fillAnswer,
  examCollect,
  examCheat,
  examQuList,
} from '@/api/user/exam'
import QuestionCardSection from '@/components/QuestionCardSection.vue'
import ExamSummaryDialog from '@/components/ExamSummaryDialog.vue'

const router = useRouter()
const route = useRoute()

// 响应式状态
const examId = ref('')
const receivedRow = ref(null)
const isFullscreen = ref(false)
const showPrevious = ref(false)
const showNext = ref(true)
const loading = ref(false)
const handleText = ref('交卷')
const saqTextarea = ref('')
const pageLoading = ref(false)
const paperId = ref('')
const cardItem = ref({})
const allItem = ref([])
const tipsFlag = ref(false)
const examPreVisible = ref(false)
const quData = ref({
  answerList: [],
})
const testData = ref({})
const pkExam = ref(null)
const examMeg = ref('')
const paperData = ref({
  leftSeconds: 99999,
  radioList: [],
  multiList: [],
  judgeList: [],
  saqList: [],
})
const radioValue = ref('')
const multiValue = ref([])
const answeredIds = ref([])
const recordData = ref([])
const submittedAnswers = ref({})
const remainingSeconds = ref(0)
const timerId = ref(null)

// 格式化时间的计算属性
const timerDisplay = computed(() => {
  const hours = Math.floor(remainingSeconds.value / 3600)
  const minutes = Math.floor((remainingSeconds.value % 3600) / 60)
  const seconds = remainingSeconds.value % 60

  return [
    hours.toString().padStart(2, '0'),
    minutes.toString().padStart(2, '0'),
    seconds.toString().padStart(2, '0'),
  ].join(':')
})

// 定时器相关方法
const startTimer = () => {
  if (timerId.value) {
    clearInterval(timerId.value)
  }

  // 初始化剩余时间
  remainingSeconds.value = paperData.value.leftSeconds || 0

  // 设置定时器，每秒更新一次
  timerId.value = setInterval(() => {
    if (remainingSeconds.value > 0) {
      remainingSeconds.value--
    } else {
      // 时间到，自动交卷
      clearInterval(timerId.value)
      handleTimeout()
    }
  }, 1000)
}

const stopTimer = () => {
  if (timerId.value) {
    clearInterval(timerId.value)
    timerId.value = null
  }
}

// 监听 paperData.leftSeconds 变化
watch(
  () => paperData.value.leftSeconds,
  (newValue) => {
    if (newValue && newValue > 0) {
      remainingSeconds.value = newValue
      // 如果定时器没有启动，则启动定时器
      if (!timerId.value) {
        startTimer()
      }
    }
  }
)

// 生命周期钩子
onMounted(() => {
  try {
    examId.value = localStorage.getItem('examId')
    // 如果没有考试ID，返回上一页
    if (!examId.value) {
      ElMessage.error('没有有效的考试ID')
      router.back()
      return
    }

    paperId.value = examId.value
    startExam(examId.value)
    fetchData(examId.value)

    document.addEventListener('visibilitychange', pageHidden)
    nextTick(() => {
      const body = document.querySelector('body')
      body.style.overflow = 'auto'
    })
  } catch (error) {
    console.error('初始化考试页面出错:', error)
    ElMessage.error('加载考试出错，请重试')
    router.back()
  }
})

onBeforeUnmount(() => {
  document.removeEventListener('visibilitychange', pageHidden)
  // 清除定时器
  stopTimer()
})

// 检查问题列表是否存在
const hasQuestions = (list) => {
  return list && list.length > 0
}

// 检查选项是否被选中
const isCheck = (myOption, sort) => {
  if (!myOption) return false
  const arr = myOption.split(',').map(Number)
  return arr.includes(sort)
}

// 处理对话框关闭
const handleClose = () => {
  examPreVisible.value = false
  // 不执行任何其他操作，仅关闭对话框
}

// 将0-5转换为A-F
const numberToLetter = (input) => {
  if (input === null || input === undefined) return ''

  const numberToCharMap = {
    0: 'A',
    1: 'B',
    2: 'C',
    3: 'D',
    4: 'E',
    5: 'F',
  }

  // 处理单个数字
  if (typeof input === 'number' || /^\d+$/.test(input)) {
    return numberToCharMap[parseInt(input, 10)] || ''
  }

  // 处理逗号分隔的数字
  if (/^\d+(,\d+)*$/.test(input)) {
    return input
      .split(',')
      .map((num) => numberToCharMap[parseInt(num.trim(), 10)] || '')
      .join(',')
  }

  return ''
}

// 转换考试数据为汇总所需格式
const transformExamData = (apiData, questionList) => {
  if (!apiData || !Array.isArray(apiData) || apiData.length === 0) {
    // 当API返回数据为空时，使用默认空数组
    console.error('API返回数据为空或非数组')
    return []
  }

  try {
    console.log('题目列表长度:', questionList.length)

    // 确保返回非空数组
    const transformed = apiData
      .map((item) => {
        console.log(
          '处理题目:',
          item.id,
          '类型:',
          item.quType,
          '答案:',
          item.myAnswer
        )

        // 在questionList中查找匹配的问题
        const question = questionList.find((q) => q.questionId === item.id)
        if (!question) {
          console.warn('未找到匹配的题目:', item.id)
        }

        // 处理选项数据
        let optionList = []
        if (Array.isArray(item.answerOptionList)) {
          optionList = item.answerOptionList.map((opt, index) => ({
            ...opt,
            sort: opt.sort !== undefined ? opt.sort : index, // 确保每个选项都有sort值
          }))
        }

        // 确保每个选项都有正确的属性
        optionList.forEach((opt) => {
          if (opt.content === undefined) opt.content = ''
          if (opt.id === undefined) opt.id = 0
        })

        // 返回转换后的数据
        return {
          id: item.id,
          title: item.title || '未知题目',
          quType: item.quType || 0,
          myOption: item.myAnswer || '',
          option: optionList,
          image: item.image || '',
          isRight: item.isRight || -1,
          sort: question ? question.sort : 0,
        }
      })
      .sort((a, b) => a.sort - b.sort) // 按照题目顺序排序

    console.log('转换后的数据条数:', transformed.length)
    return transformed
  } catch (error) {
    console.error('转换数据出错:', error)
    // 出错时返回空数组，但同时打印详细错误
    console.error('API数据:', JSON.stringify(apiData))
    console.error('题目列表:', questionList.length)
    return []
  }
}

// 交卷前预览
const handHandExamPre = () => {
  handSave(cardItem.value)
  examCollect(examId.value)
    .then((res) => {
      console.log('examCollect返回数据:', res.data)
      console.log('allItem数据:', allItem.value)

      // 检查是否有错误信息
      if (res.msg && res.msg.includes('没有考试在进行')) {
        ElMessage.error('没有考试在进行')
        router.back() // 返回上一页
        return
      }

      if (!res.data || !Array.isArray(res.data) || res.data.length === 0) {
        // 即使没有答题数据，也允许交卷
        ElMessage.warning('暂无有效答题数据')
        // 弹出确认对话框，询问是否继续交卷
        ElMessageBox.confirm('暂无有效答题数据，是否确认交卷？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            doHandler() // 直接调用交卷函数
          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: '交卷已取消，您可以继续作答！',
            })
          })
        return
      }

      console.log('处理前的API数据:', JSON.stringify(res.data))

      // 转换API返回的数据为汇总对话框所需格式
      recordData.value = transformExamData(res.data, allItem.value)
      console.log('转换后的recordData:', JSON.stringify(recordData.value))

      // 检查转换后的数据
      if (!recordData.value || recordData.value.length === 0) {
        ElMessage.warning('处理答题数据异常，请重试')
        return
      }

      // 显示对话框
      examPreVisible.value = true
    })
    .catch((error) => {
      console.error('获取考试数据出错:', error)
      // 检查是否包含特定错误信息
      if (
        error.response &&
        error.response.data &&
        error.response.data.msg === '没有考试在进行'
      ) {
        ElMessage.error('没有考试在进行')
        router.back() // 返回上一页
      } else {
        // 即使获取数据失败，也允许交卷
        ElMessageBox.confirm('获取答题数据失败，是否继续交卷？', '提示', {
          confirmButtonText: '继续交卷',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            doHandler() // 直接调用交卷函数
          })
          .catch(() => {
            ElMessage({
              type: 'info',
              message: '交卷已取消，您可以继续作答！',
            })
          })
      }
    })
}

// 切换页面检测
const pageHidden = (e = null) => {
  if (document.visibilityState === 'hidden') {
    examCheat(examId.value).then((res) => {
      if (res.code) {
        examMeg.value = res.msg
        tipsFlag.value = true
        if (res.data) {
          // 清除localStorage中的考试ID
          localStorage.removeItem('examId')

          // 回退到学生主页
          router.push({ name: 'StudentExam' })
        }
      }
    })
  }
}

// 开始考试
const startExam = (examId) => {
  examQuList(examId)
    .then((res) => {
      // 检查是否有错误信息
      if (res.msg && res.msg.includes('没有考试在进行')) {
        ElMessage.error('没有考试在进行')
        router.back() // 返回上一页
        return
      }

      paperData.value = res.data

      // 启动倒计时
      startTimer()
    })
    .catch((error) => {
      console.error('获取考试列表出错:', error)
      // 检查是否包含特定错误信息
      if (
        error.response &&
        error.response.data &&
        error.response.data.msg === '没有考试在进行'
      ) {
        ElMessage.error('没有考试在进行')
        router.back() // 返回上一页
      } else {
        ElMessage.error('获取考试列表失败')
      }
    })
}

/**
 * 统计有多少题没答的
 * @returns {number}
 */
const countNotAnswered = () => {
  let notAnswered = 0
  const checkList = (list) => {
    if (list) {
      list.forEach((item) => {
        if (!item.checkout) {
          notAnswered += 1
        }
      })
    }
  }

  checkList(paperData.value.radioList)
  checkList(paperData.value.multiList)
  checkList(paperData.value.judgeList)
  checkList(paperData.value.saqList)

  return notAnswered
}

/**
 * 下一题
 */
const handNext = () => {
  const index = cardItem.value.sort + 1
  if (index < allItem.value.length) {
    handSave(allItem.value[index])
  }
}

/**
 * 上一题
 */
const handPrevious = () => {
  const index = cardItem.value.sort - 1
  if (index >= 0) {
    handSave(allItem.value[index])
  }
}

// 清空Session
// 使用函数清除以 "exam_" 开头的所有键值对
const clearSessionStorageByPrefix = (prefix) => {
  Object.keys(sessionStorage)
    .filter((key) => key.startsWith(prefix))
    .forEach((key) => sessionStorage.removeItem(key))
}

// 交卷
const doHandler = () => {
  // 关闭考前汇总对话框
  examPreVisible.value = false

  const notAnswered = countNotAnswered()
  const msg =
    notAnswered > 0
      ? `您还有${notAnswered}题未作答，确认要交卷吗?`
      : '确认要交卷吗？'

  ElMessageBox.confirm(msg, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      handleText.value = '正在交卷，请等待...'
      loading.value = true

      handExam(examId.value)
        .then(() => {
          ElMessage({
            message: '试卷提交成功！',
            type: 'success',
          })
          clearSessionStorageByPrefix('exam_')

          // 清除localStorage中的考试ID
          localStorage.removeItem('examId')

          // 回退到学生主页
          router.push({ name: 'StudentExam' })
        })
        .catch((error) => {
          console.error('交卷出错:', error)
          loading.value = false
          handleText.value = '交卷'
          ElMessage.error('交卷失败，请重试')
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '交卷已取消，您可以继续作答！',
      })
    })
}

// 保存答案
const handSave = (item, callback) => {
  // 更新上一题/下一题按钮状态
  showPrevious.value = item.sort > 0
  showNext.value = item.sort < allItem.value.length - 1

  // 保存当前题目的引用，以便在回调中更新其状态
  const currentItem = cardItem.value

  // 获取题目ID
  const questionId = cardItem.value.questionId
  // 判断题目类型
  const isSimpleAnswer = allItem.value[cardItem.value.sort]?.type === 4

  // 准备答案数据
  let answerContent = ''
  if (isSimpleAnswer) {
    console.log('简答题')
    console.log(saqTextarea.value)
    // 简答题答案
    answerContent = saqTextarea.value
    // 清空输入框
    saqTextarea.value = ''
  } else {
    console.log('单选、多选、判断题')
    // 单选、多选、判断题答案
    const answers = [...multiValue.value]
    if (radioValue.value != '') {
      answers.push(radioValue.value)
    }
    answerContent = answers.join(',')
  }

  // 检查是否有答案，如果没有答案且不是强制提交（如交卷前），则不提交
  const hasAnswer = isSimpleAnswer
    ? !!answerContent.trim()
    : answerContent != ''
  console.log('hasAnswer:', hasAnswer)
  // 检查是否已经提交过相同的答案
  const previousAnswer = submittedAnswers.value[questionId]
  const answerUnchanged = previousAnswer === answerContent

  // 如果答案已提交且未更改，且不是强制提交（callback不存在），则跳过提交
  if (
    answerUnchanged &&
    !callback &&
    sessionStorage.getItem('exam_' + questionId) === '1'
  ) {
    console.log('答案未更改，跳过提交')
    // 直接加载下一题
    fetchQuData(item)
    return
  }

  // 如果有答案或者是强制提交（callback存在），则提交答案
  if (hasAnswer || callback) {
    const params = {
      examId: paperId.value,
      quId: questionId,
      answer: answerContent,
    }
    // 对于多选题，需要对答案进行排序
    if (quData.value.quType === 2 && answerContent) {
      // 将答案ID转为数组，排序后再转回字符串
      const sortedAnswers = answerContent
        .split(',')
        .map((id) => parseInt(id))
        .sort((a, b) => {
          // 查找对应选项的sort值进行排序
          const itemA = quData.value.answerList.find((item) => item.id === a)
          const itemB = quData.value.answerList.find((item) => item.id === b)
          return (itemA?.sort || 0) - (itemB?.sort || 0)
        })
        .join(',')

      params.answer = sortedAnswers
    }
    fillAnswer(params).then((res) => {
      if (res.code) {
        // 标记为已答
        sessionStorage.setItem('exam_' + currentItem.questionId, '1')

        // 保存已提交的答案，用于后续比较
        submittedAnswers.value[questionId] = answerContent

        // 更新当前题目的状态
        updateQuestionStatus(currentItem.questionId, 1)
      } else {
        // 标记为未答
        sessionStorage.setItem('exam_' + currentItem.questionId, '0')
        updateQuestionStatus(currentItem.questionId, 0)
      }

      // 最后一个动作，交卷
      if (callback) {
        callback()
      }
      // 查找详情
      fetchQuData(item)
    })
  } else {
    // 确保不标记为已答题
    sessionStorage.setItem('exam_' + currentItem.questionId, '0')
    updateQuestionStatus(currentItem.questionId, 0)

    // 查找详情
    fetchQuData(item)
  }
}

// 更新题目状态
const updateQuestionStatus = (questionId, status) => {
  // 在所有题型列表中查找并更新状态
  const updateListStatus = (list) => {
    if (list && list.length > 0) {
      const question = list.find((q) => q.questionId === questionId)
      if (question) {
        question.checkout = status
      }
    }
  }

  updateListStatus(paperData.value.radioList)
  updateListStatus(paperData.value.multiList)
  updateListStatus(paperData.value.judgeList)
  updateListStatus(paperData.value.saqList)
}

// 提交最后一题答案
const submitLastAnswer = () => {
  // 获取题目ID
  const questionId = cardItem.value.questionId
  // 判断题目类型
  const isSimpleAnswer = allItem.value[cardItem.value.sort]?.type === 4

  // 准备答案数据
  let answerContent = ''
  if (isSimpleAnswer) {
    // 简答题答案
    answerContent = saqTextarea.value
  } else {
    // 单选、多选、判断题答案
    const answers = [...multiValue.value]
    if (radioValue.value != '') {
      answers.push(radioValue.value)
    }
    answerContent = answers.join(',')
  }

  // 检查是否有答案
  const hasAnswer = isSimpleAnswer
    ? !!answerContent.trim()
    : answerContent != ''

  if (hasAnswer) {
    const params = {
      examId: paperId.value,
      quId: questionId,
      answer: answerContent,
    }

    // 对于多选题，需要对答案进行排序
    if (quData.value.quType === 2 && answerContent) {
      // 将答案ID转为数组，排序后再转回字符串
      const sortedAnswers = answerContent
        .split(',')
        .map((id) => parseInt(id))
        .sort((a, b) => {
          // 查找对应选项的sort值进行排序
          const itemA = quData.value.answerList.find((item) => item.id === a)
          const itemB = quData.value.answerList.find((item) => item.id === b)
          return (itemA?.sort || 0) - (itemB?.sort || 0)
        })
        .join(',')

      params.answer = sortedAnswers
    }

    fillAnswer(params).then((res) => {
      if (res.code) {
        // 标记为已答
        sessionStorage.setItem('exam_' + questionId, '1')

        // 保存已提交的答案，用于后续比较
        submittedAnswers.value[questionId] = answerContent

        // 更新当前题目的状态
        updateQuestionStatus(questionId, 1)

        ElMessage({
          message: '答案提交成功！',
          type: 'success',
        })
      } else {
        // 标记为未答
        sessionStorage.setItem('exam_' + questionId, '0')
        updateQuestionStatus(questionId, 0)

        ElMessage({
          message: '答案提交失败，请重试！',
          type: 'error',
        })
      }
    })
  } else {
    ElMessage({
      message: '请先填写答案再提交！',
      type: 'warning',
    })
  }
}

// 试卷详情
const fetchQuData = (item) => {
  // 打开
  const loading = ElLoading.service({
    text: '拼命加载中',
    background: 'rgba(0, 0, 0, 0.7)',
  })

  // 获得详情
  cardItem.value = item
  const examId = localStorage.getItem('examId')
  // 查找下个详情
  const params = { examId: examId, questionId: item.questionId }
  quDetail(params)
    .then((response) => {
      quData.value = response.data
      radioValue.value = ''
      multiValue.value = []

      // 根据题目类型设置答案
      if (response.data.quType === 4 && response.data.answerList != null) {
        // 简答题
        saqTextarea.value = response.data.answerList[0].content

        // 记录当前加载的答案
        if (sessionStorage.getItem('exam_' + item.questionId) === '1') {
          submittedAnswers.value[item.questionId] = saqTextarea.value
        }
      } else if (
        response.data.quType === 1 ||
        response.data.quType === 2 ||
        response.data.quType === 3
      ) {
        // 单选、多选、判断题
        response.data.answerList.forEach((item) => {
          if (
            (response.data.quType === 1 || response.data.quType === 3) &&
            item.checkout
          ) {
            radioValue.value = item.id
          }
          if (response.data.quType === 2 && item.checkout) {
            multiValue.value.push(item.id)
          }
        })
      }

      // 关闭加载提示
      loading.close()
    })
    .catch(() => {
      // 出错时也要关闭加载提示
      loading.close()
    })
}

// 试卷详情
const fetchData = (examId) => {
  examQuList(examId)
    .then((response) => {
      // 检查是否有错误信息
      if (response.msg && response.msg.includes('没有考试在进行')) {
        ElMessage.error('没有考试在进行')
        router.back() // 返回上一页
        return
      }

      // 试卷内容
      paperData.value = response.data
      allItem.value = []

      // 获得第一题内容
      setFirstQuestion()

      // 合并所有题目到allItem数组
      mergeAllQuestions()

      // 当前选定
      fetchQuData(cardItem.value)
    })
    .catch((error) => {
      console.error('获取试卷详情出错:', error)
      // 检查是否包含特定错误信息
      if (
        error.response &&
        error.response.data &&
        error.response.data.msg === '没有考试在进行'
      ) {
        ElMessage.error('没有考试在进行')
        router.back() // 返回上一页
      } else {
        ElMessage.error('获取试卷详情失败')
      }
    })
}

// 设置第一个题目
const setFirstQuestion = () => {
  if (paperData.value.radioList && paperData.value.radioList.length > 0) {
    cardItem.value = paperData.value.radioList[0]
  } else if (
    paperData.value.multiList &&
    paperData.value.multiList.length > 0
  ) {
    cardItem.value = paperData.value.multiList[0]
  } else if (
    paperData.value.judgeList &&
    paperData.value.judgeList.length > 0
  ) {
    cardItem.value = paperData.value.judgeList[0]
  } else if (paperData.value.saqList && paperData.value.saqList.length > 0) {
    cardItem.value = paperData.value.saqList[0]
  }
}

// 合并所有题目
const mergeAllQuestions = () => {
  const addQuestionsToAllItems = (questionList) => {
    if (questionList && questionList.length > 0) {
      questionList.forEach((item) => allItem.value.push(item))
    }
  }

  addQuestionsToAllItems(paperData.value.radioList)
  addQuestionsToAllItems(paperData.value.multiList)
  addQuestionsToAllItems(paperData.value.judgeList)
  addQuestionsToAllItems(paperData.value.saqList)
}

// 处理滚动事件
const handleScroll = () => {
  // 实现滚动逻辑
}

// 获取左侧距离
const getLfetDistance = () => {
  const body = document.querySelector('body')
  const flexLeft = (body.offsetWidth - 1200) / 2
}

// 处理考试超时
const handleTimeout = () => {
  console.log('考试时间已到，自动交卷')

  ElMessage({
    message: '考试时间已到，系统将自动交卷',
    type: 'warning',
    duration: 5000,
  })

  // 显示交卷中状态
  handleText.value = '正在交卷...'
  loading.value = true

  // 自动交卷
  handExam(examId.value)
    .then(() => {
      ElMessage({
        message: '试卷已自动提交！',
        type: 'success',
      })
      clearSessionStorageByPrefix('exam_')

      // 清除localStorage中的考试ID
      localStorage.removeItem('examId')

      // 回退到学生主页
      router.push({ name: 'StudentExam' })
    })
    .catch((error) => {
      console.error('自动交卷出错:', error)
      loading.value = false
      handleText.value = '交卷'
      ElMessage.error('自动交卷失败，请手动交卷')
    })
}

// 添加返回首页功能
const confirmReturn = () => {
  ElMessageBox.confirm(
    '确认要退出考试并返回首页吗？所有未提交的答案将丢失！',
    '警告',
    {
      confirmButtonText: '确认退出',
      cancelButtonText: '取消',
      type: 'warning',
      distinguishCancelAndClose: true,
    }
  )
    .then(() => {
      // 清除localStorage中的考试ID
      localStorage.removeItem('examId')
      clearSessionStorageByPrefix('exam_')

      // 退出到学生主页
      ElMessage({
        message: '已退出考试',
        type: 'info',
      })
      router.push({ name: 'StudentExam' })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消退出，您可以继续作答',
      })
    })
}
</script>

<style scoped>
page {
  background: #ebecee;
}

.qu-content div {
  line-height: 30px;
  width: 100%;
}

.el-checkbox-group label,
.el-radio-group label {
  width: 100%;
}

.content-h {
  height: calc(100vh - 110px);
  overflow-y: auto;
}

.card-title {
  background: #eee;
  line-height: 35px;
  text-align: center;
  font-size: 14px;
}
.card-line {
  padding-left: 10px;
  display: flex;
  flex-wrap: wrap;
}
.card-line span {
  cursor: pointer;
  margin: 2px;
}

::v-deep .el-radio,
.el-checkbox {
  padding: 9px 20px 9px 10px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  margin-bottom: 10px;
  width: 100%;
}

.is-checked {
  border: #409eff 1px solid;
}

.el-radio img,
.el-checkbox img {
  max-width: 200px;
  max-height: 200px;
  border: #dcdfe6 1px dotted;
}

::v-deep .el-checkbox__inner {
  display: none;
}

::v-deep .el-radio__inner {
  display: none;
}

::v-deep .el-checkbox__label {
  line-height: 30px;
}

::v-deep .el-radio__label {
  line-height: 30px;
}

/* 考试记录 */
.content {
  width: 97%;
  height: 60px;
  border: 1px solid #0a84ff;
  margin-top: 8px;
  margin-left: 10px;
  padding: 10px;
  font-weight: 200;
}
.sj {
  margin-top: 10px;
  margin-left: 10px;
  line-height: 22px;
}
.fk {
  width: 200px;
  height: 100%;
  box-shadow: 0 0 15px rgb(197, 197, 197);
  margin: auto;
  margin-top: 20px;
  margin-left: 15px;
}
.el-header {
  background-color: #b3c0d1;
  color: #333;
  line-height: 60px;
}

.left {
  width: 250px;
  height: 100%;
}
.right {
  width: 70%;
  height: 100%;
}
.el-divider--horizontal {
  display: block;
  height: 1px;
  width: 95%;
  margin: 24px 0;
}
.type_tag {
  margin-right: 5px;
  margin-top: 10px;
}

/* // 试题内容样式 */
.qu_list {
  height: 100%;
  width: 100%;
  overflow: auto;
  page-break-after: always;

  .qu_num {
    display: inline-block;
    /* // background: url('~@/assets/images/tkxl/btbj.png') no-repeat 100% 100%; */
    background-size: contain;
    height: 30px;
    width: 30px;
    line-height: 25px;
    color: #fff;
    font-size: 14px;
    text-align: center;
    margin-right: 15px;
    flex-shrink: 0;
  }

  .qu_content {
    padding-left: 10px;
  }

  /* // 选项组 */
  .qu_choose_group {
    width: 100%;

    /* 单个选项 */
    .qu_choose {
      display: block;
      margin: 10px;
      .el-radio__label {
        line-height: 20px;
      }
      /* // 去除前面的radio */
      ::v-deep .el-radio__input .el-radio__inner {
        display: none;
      }

      /* // 单个选项内容样式 */
      .qu_choose_tag {
        display: inline-flex;
        width: 90%;
        /* // 选项标签 */
        .qu_choose_tag_type {
          font-weight: bold;
          /* // color: #0a84ff; */
          width: 10px;
        }
        /* // 选项内容 */
        .qu_choose_tag_content {
          padding: 0 10px 10px 10px;
        }

        .qu_choose_tag_el_image {
          clear: both;
          padding-top: 10px;
        }
      }
      /* // 选项答案 */
      .qu_choose_answer {
        float: right;
      }
    }
  }

  /* // 试题解析 */
  .qu_analysis {
    padding: 10px;

    .qu_analysis_content {
      padding-top: 10px;
    }
  }

  /* // 试题赋分 */
  .qu_assign_score {
    background: #f5f5f5;
    height: 100px;
    padding-top: 35px;

    .qu_assign_score_content {
      width: 80px;
    }
  }
}
.current {
  background: #f5f5f5;
}
.imgC {
  height: 150px;
}
.qu_choose_tag_img {
  height: auto;
  display: block;
  margin: 10px;
}
</style>
